/**
 * AI服务类 - DeepSeek API集成
 * 负责调用DeepSeek API解析用户自然语言意图
 */

const axios = require('axios');
const config = require('../config/config');

class AIService {
  constructor() {
    this.apiKey = config.deepseek.apiKey;
    this.apiUrl = config.deepseek.apiUrl;
    this.model = config.deepseek.model;
    this.timeout = config.deepseek.timeout;
  }

  /**
   * 调用DeepSeek API解析用户意图
   * @param {string} userMessage - 用户输入的自然语言
   * @returns {Promise<Object>} - 解析后的操作指令
   */
  async parseUserIntent(userMessage) {
    try {
      console.log('正在调用DeepSeek API解析用户意图:', userMessage);

      const requestData = {
        model: this.model,
        messages: [
          {
            role: 'system',
            content: config.prompts.system
          },
          {
            role: 'user',
            content: userMessage
          }
        ],
        max_tokens: 1000,
        temperature: 0.3
      };

      const response = await axios.post(this.apiUrl, requestData, {
        headers: {
          'Authorization': `Bearer ${this.apiKey}`,
          'Content-Type': 'application/json',
          'User-Agent': 'AI-Table-Manager/1.0'
        },
        timeout: this.timeout,
        httpsAgent: new (require('https').Agent)({
          keepAlive: true,
          timeout: this.timeout,
          rejectUnauthorized: true
        }),
        maxRetries: 3,
        retryDelay: 1000
      });

      if (response.data && response.data.choices && response.data.choices[0]) {
        const aiResponse = response.data.choices[0].message.content.trim();
        console.log('DeepSeek API响应:', aiResponse);

        try {
          // 尝试解析JSON响应
          const parsedResponse = JSON.parse(aiResponse);
          return {
            success: true,
            data: parsedResponse
          };
        } catch (parseError) {
          console.error('解析AI响应JSON失败:', parseError.message);
          return {
            success: false,
            error: 'AI响应格式错误',
            rawResponse: aiResponse
          };
        }
      } else {
        throw new Error('DeepSeek API响应格式异常');
      }

    } catch (error) {
      console.error('调用DeepSeek API失败:', error.message);

      if (error.response) {
        console.error('API错误响应:', error.response.data);
        return {
          success: false,
          error: `API调用失败: ${error.response.status} - ${error.response.data.error?.message || '未知错误'}`
        };
      } else if (error.request) {
        return {
          success: false,
          error: 'API请求超时或网络错误'
        };
      } else {
        return {
          success: false,
          error: `处理请求时发生错误: ${error.message}`
        };
      }
    }
  }

  /**
   * 生成智能回复
   * @param {string} userMessage - 用户消息
   * @param {Object} operationResult - 操作结果
   * @returns {Promise<string>} - 智能回复
   */
  async generateSmartReply(userMessage, operationResult) {
    try {
      const contextMessage = `
用户请求：${userMessage}
操作结果：${JSON.stringify(operationResult)}

请生成一个友好、自然的回复消息，总结操作结果。如果操作成功，要体现具体的操作内容；如果失败，要说明失败原因并给出建议。
`;

      const requestData = {
        model: this.model,
        messages: [
          {
            role: 'system',
            content: '你是一个友好的AI助手，负责将数据库操作结果转换为自然的对话回复。回复要简洁明了，语气友好。'
          },
          {
            role: 'user',
            content: contextMessage
          }
        ],
        max_tokens: 200,
        temperature: 0.7
      };

      const response = await axios.post(this.apiUrl, requestData, {
        headers: {
          'Authorization': `Bearer ${this.apiKey}`,
          'Content-Type': 'application/json',
          'User-Agent': 'AI-Table-Manager/1.0'
        },
        timeout: this.timeout,
        httpsAgent: new (require('https').Agent)({
          keepAlive: true,
          timeout: this.timeout,
          rejectUnauthorized: true
        }),
        maxRetries: 3,
        retryDelay: 1000
      });

      if (response.data && response.data.choices && response.data.choices[0]) {
        return response.data.choices[0].message.content.trim();
      } else {
        return '操作已完成。';
      }

    } catch (error) {
      console.error('生成智能回复失败:', error.message);
      return '操作已完成。';
    }
  }
}

module.exports = AIService;